use winapi::shared::minwindef::HMODULE;
use crate::win::processes;
use crate::win::kernel32::{policyholder, process};
use encoding_rs::{UTF_8, WINDOWS_1252};
use regex::Regex;

// 禁用 DEP 执行保护
pub fn disable_dep() {
    if policyholder::get_system_deppolicy() < 2 {
        if !policyholder::set_process_deppolicy(0) {
            println!("Failed to disable DEP");
            std::process::exit(1);
        }
    }
}

// 获取 WeChat.exe 进程
pub fn get_processes_wechat(index: i32) -> Vec<u32> {
    let processes = processes::get_processes_by_name("WeChat.exe");
    if index == -1 {
        processes
    } else if index >= 0 && (index as usize) < processes.len() {
        vec![processes[index as usize]]
    } else {
        vec![0]
    }
}

// 获取 WeChat.exe 模块句柄
pub unsafe fn get_wechat_module_handle(pid: u32) -> HMODULE {
    process::get_specified_module_handle(pid, "WeChatWin.dll".to_string())
}

fn unicode_to_ansi(input: &str) -> String {
    let (bytes, _, _) = WINDOWS_1252.encode(input);
    String::from_utf8_lossy(&bytes).to_string().replace("\0", "")
}

#[allow(dead_code)]
fn utf8_to_unicode(input: &str) -> String {
    let (cow, _, _) = UTF_8.decode(input.as_bytes());
    cow.into_owned()
}

fn is_sim(phone_number: String) -> String {
    let re = Regex::new(r"^1[3-9]\d{9}$").unwrap();
    if re.is_match(&*phone_number) {
        phone_number
    } else {
        "None".to_string()
    }
}

// 获取微信版本
pub unsafe fn get_wechat_version(pid: u32) -> String {
    let we_chat_win_dll = get_wechat_module_handle(pid);
    let bytes = process::read_memory(pid as i32, we_chat_win_dll as u64 + process::hex_to_decimal("22551CE"), 16);
    unicode_to_ansi(bytes.as_str())
}

// 获取微信登录二维码
pub unsafe fn get_wechat_login_qrcode(pid: u32) -> String {
    let we_chat_win_dll = get_wechat_module_handle(pid);
    let init_addr = process::read_memory_int(pid as i32, (we_chat_win_dll as u64 + process::hex_to_decimal("22580A0")) as u64).unwrap();
    let bytes = process::read_memory(pid as i32, init_addr as u64, 20);
    if bytes == "".to_string() {
        "None".to_string()
    } else {
        format!("http://weixin.qq.com/x/{}", bytes)
    }
}

// 获取微信登录状态
pub unsafe fn get_wechat_login_state(pid: u32) -> u8 {
    let we_chat_win_dll = get_wechat_module_handle(pid);
    let is_send_login_data = process::read_memory_byte(pid as i32, (we_chat_win_dll as u64 + process::hex_to_decimal("21850F5")) as u64).unwrap();
    if is_send_login_data == 1 {
        let is_login = process::read_memory_byte(pid as i32, (we_chat_win_dll as u64 + process::hex_to_decimal("222EFF8")) as u64).unwrap();
        if is_login == 1 {
            2
        } else {
            1
        }
    } else {
        0
    }
}

pub unsafe fn get_wechat_personal_data(pid: u32) {
    let we_chat_win_dll = get_wechat_module_handle(pid);
    let base_address = process::hex_to_decimal("222EBB4");
    // 取微信昵称
    let user_name = process::read_memory(pid as i32, we_chat_win_dll as u64 + base_address, 100);
    // 取微信绑定的手机号
    let user_sim = is_sim(process::read_memory(pid as i32, we_chat_win_dll as u64 + base_address + process::hex_to_decimal("34"), 100));
    // 取微信绑定的QQ号
    let mut user_oicq = process::read_memory_int(pid as i32, we_chat_win_dll as u64 + base_address + process::hex_to_decimal("4C")).unwrap().to_string();
    user_oicq = if user_oicq == "0".to_string() {
        "None".to_string()
    } else {
        user_oicq
    };
    // 取微信ID
    let user_id_init_addr = process::read_memory_int(pid as i32, we_chat_win_dll as u64 + base_address + process::hex_to_decimal("46C")).unwrap();
    let user_id = process::read_memory(pid as i32, user_id_init_addr as u64, 20);
    // 取微信号
    let user_uin = process::read_memory(pid as i32, (we_chat_win_dll as u64 + base_address + process::hex_to_decimal("17C")) as u64, 100);
    // 取微信登录设备
    let user_device = process::read_memory(pid as i32, (we_chat_win_dll as u64 + base_address + process::hex_to_decimal("4A4")) as u64, 100);
    // 取微信头像地址
    let user_head_image_init_addr = process::read_memory_int(pid as i32, we_chat_win_dll as u64 + base_address + process::hex_to_decimal("2E0")).unwrap();
    let user_head_image = process::read_memory(pid as i32, user_head_image_init_addr as u64, 150);
    // 取微信国籍
    let user_nationality = process::read_memory(pid as i32, (we_chat_win_dll as u64 + process::hex_to_decimal("222EF30")) as u64, 100);
    // 取微信绑定的邮箱
    let mut user_mailbox_init_addr = process::read_memory_int(pid as i32, we_chat_win_dll as u64 + base_address + process::hex_to_decimal("1C")).unwrap();
    user_mailbox_init_addr = process::read_memory_int(pid as i32, user_mailbox_init_addr as u64).unwrap();
    let mut user_mailbox = process::read_memory(pid as i32, (user_mailbox_init_addr + 1) as u64, 100);
    user_mailbox = if user_mailbox == "".to_string() {
        "None".to_string()
    } else {
        user_mailbox
    };
    println!("User Name: {}", user_name);
    println!("User SIM: {}", user_sim);
    println!("User OICQ: {}", user_oicq);
    println!("User Id: {}", user_id);
    println!("User Uin: {}", user_uin);
    println!("User Device: {}", user_device);
    println!("User HeadImage: {}", user_head_image);
    println!("User Nationality: {}", user_nationality);
    println!("User Mailbox: {}", user_mailbox);
}